package ksu_product.proGen.service.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;




import org.apache.commons.lang.StringUtils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import ksu_product.proGen.dao.GeneratorDAO;
import ksu_product.proGen.dto.TableDTO;
import ksu_product.proGen.dto.TemplateDTO;
import ksu_product.proGen.service.GeneratorService;
import ksu_product.proGen.util.Contants;
import ksu_product.proGen.util.MyUtils;
import ksu_product.proGen.util.SystemConfig;

public class GeneratorServiceImpl implements GeneratorService {

	private GeneratorDAO generatorDAO;

	public void setGeneratorDAO(GeneratorDAO generatorDAO) {
		this.generatorDAO = generatorDAO;
	}
	
	@SuppressWarnings("unchecked")
	public List<TableDTO> getTableInfo(TableDTO tableDTO){
		return (List<TableDTO>)generatorDAO.selectList(Contants.TABLE_SELECT, tableDTO);
	}

	@Override
	public void createClass(List<TableDTO> tableColumnList,TableDTO tableDTO) {
		if(tableColumnList != null && tableColumnList.size() > 0){
			List<TemplateDTO> templateList = SystemConfig.getTemplateList();
			if(templateList != null && templateList.size() > 0){
				for(TemplateDTO template : templateList){
					freeMarkerCreate(template,tableColumnList,tableDTO);
				}
			}
		}	
	}
	
	private void freeMarkerCreate(TemplateDTO template,List<TableDTO> tableColumnList,TableDTO tableDTO){
		Configuration cfg = new Configuration();
		try {
			cfg.setDirectoryForTemplateLoading(new File(SystemConfig.TEMPLATE_PATH));
			cfg.setObjectWrapper(new DefaultObjectWrapper()); 
			Map<String,Object> root = new HashMap<String,Object>();
			Template classTemplate = cfg.getTemplate(template.getTemplateName()); 
			String newFileName = null;
			if(SystemConfig.NO_PREFIX.equals("false")){
			    newFileName = StringUtils.replace(template.getFileName(),"#className#",StringUtils.capitalize(tableDTO.getClassName()));
			}else{
				newFileName = StringUtils.replace(template.getFileName(),"#className#",StringUtils.capitalize(tableDTO.getClassNameNoPrefix()));
			}
			File file = new File(SystemConfig.FILE_OUTPUT_PATH);
			if(!file.exists()){
				file.mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(SystemConfig.FILE_OUTPUT_PATH + File.separator + newFileName);
			Writer out = new OutputStreamWriter(fos);
			root.put("tableColumnList", tableColumnList);
			root.put("tableDTO",tableDTO);
			root.put("currentDate", MyUtils.dateToStringNoTime(new Date()));
			classTemplate.process(root, out);
			out.flush();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String getClassName(String tableName){
		String[] fieldArray = tableName.toLowerCase().split("_");
		if(fieldArray.length <= 0){
			return tableName.toLowerCase();
		}else{
			String property = "";
			int i=0;
			for(String field : fieldArray){
				if(i == 0){
					property = field;
				}else{
					char[] propertyTemp = field.toCharArray();
					propertyTemp[0] = String.valueOf(propertyTemp[0]).toUpperCase().toCharArray()[0];
					property+=String.valueOf(propertyTemp);
				}
				i++;
			}
			return property;
		}
	}

	/**
	 * 根据数据库类型获取sql
	 * @param tableName
	 * @return
	 */
	@Override
	public String getSelectSql(String tableName) {
	    String database = generatorDAO.getSqlSession().getConfiguration().getDatabaseId();
	    if(database.equals("Microsoft SQL Server")){
	    	String sql = Contants.SQLSERVER_TABLE_SELECT_SQL;
	    	sql = StringUtils.replace(sql, "#tableName#", tableName);
	    	return sql;
	    }else if(database.equals("MySQL")){
	    	String sql = Contants.MYSQL_TABLE_SELECT_SQL;
	    	sql = StringUtils.replace(sql, "#tableName#", tableName);
	    	return sql;
	    }else if(database.equals("Oracle")){
	    	String sql = Contants.ORACLE_TABLE_SELECT_SQL;
	    	sql = StringUtils.replace(sql, "#tableName#", tableName);
	    	return sql;
	    }
	    
		return null;
	}
}
